package slice

import (
	"errors"
)

func Delete[T any](index int, slice []T) (val T, resSlice []T, err error) {
	length := len(slice)
	if (index < 0) || (index >= length) {
		return val, slice, errors.New("index out of range")
	}

	val = slice[index]
	copy(slice[index:], slice[index+1:])
	slice = slice[:length-1]
	slice = Shrink(slice)
	return val, slice, nil
}

func Shrink[T any](slice []T) (newSlice []T) {
	length, capacity := len(slice), cap(slice)
	isShrink, newCapacity := CalcShrinkCap(length, capacity)
	if !isShrink {
		return slice
	}
	newSlice = make([]T, length, newCapacity)
	copy(newSlice, slice)
	return newSlice
}

func CalcShrinkCap(length int, capacity int) (isShrink bool, newCapacity int) {
	if capacity <= 64 {
		return false, 64
	}
	if (capacity <= 512 || length < 256) && length < capacity/3 {
		return true, length * 2
	}
	if length < capacity/2 {
		return true, length + length/2
	}
	return false, capacity
}

// 去重
func DeleteDuplicate[T comparable](s []T) []T {
	return s
}

func Flat[T any](s []T) []T {
	return s
}

func Reverse[T any](s []T) {
	for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
		s[i], s[j] = s[j], s[i]
	}
}
